package com.example.weblending.controlller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.weblending.domain.File;
import com.example.weblending.domain.User;
import com.example.weblending.exception.GlobalException;
import com.example.weblending.service.FileService;
import com.example.weblending.service.UserService;
import com.example.weblending.utils.CsvUtils;
import com.example.weblending.utils.JwtUtils;
import com.example.weblending.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileController {

    @Autowired
    private FileService fileService;

    @Resource
    private UserService userService;

    @Autowired
    private CsvUtils csvUtils;

    /**
     * 获得自己上传过的文件列表
     */
    @GetMapping("list/{page}/{limit}")
    public Result getHistoryList(@PathVariable long page, @PathVariable long limit, HttpServletRequest request) {
        boolean v=JwtUtils.checkToken(request);
        if(!v){
            throw new GlobalException(20004,"请重新登录");
        }
        String id = JwtUtils.getMemberIdByJwtToken(request);
        Page<File> files=fileService.getListById(page,limit,id);
        return Result.ok().data(files).data("item",files.getRecords());
    }

    /**
     * 上传文件
     */
    @PostMapping("upload")
    @CrossOrigin(origins = "*")
    public Result saveFile(MultipartFile file,HttpServletRequest request){
        User user= JwtUtils.checkUser(request,userService);
        fileService.save(File.save(user.getUid(),file.getOriginalFilename(),csvUtils.upload(file)));
        return Result.ok();
    }

    /**
     * 删除文件，需要将数据库中的文件和分析结果删除，
     * 同时删除本地文件
     */
    @DeleteMapping("{id}")
    public Result delete(@PathVariable int id,HttpServletRequest request){
        boolean v=JwtUtils.checkToken(request);
        if(!v){
            throw new GlobalException(20004,"请重新登录");
        }
        boolean success=fileService.remove(id);
        return success?Result.ok():Result.error();
    }

    /**
     *  导出服务器本地的清洗结果
     */
    @RequestMapping("download/{id}/clean")
    @CrossOrigin(origins = "*")
    public void downloadClean(@PathVariable int id, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String uid=JwtUtils.getMemberIdByJwtToken(request);
        String path= fileService.getCleanPath(uid,id);
        java.io.File file = new java.io.File(path);
        String filename = file.getName();
        filename=filename.substring(32,filename.length()).replace(".csv","-清理结果.csv");
        setStreamResponse(response, file, filename);
    }

    /**
     *  导出服务器本地的分析结果
     */
    @RequestMapping("download/{id}/analyze")
    @CrossOrigin(origins = "*")
    public void downloadAnalyze(@PathVariable int id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uid=JwtUtils.getMemberIdByJwtToken(request);
        String path= fileService.getAnalyzePath(uid,id);
        java.io.File file = new java.io.File(path);
        String filename = file.getName();
        filename=filename.substring(32,filename.length()).replace(".csv","-分析结果.csv");
        setStreamResponse(response, file, filename);
    }

    /**
     * 为下载响应添加合适的头部
     */
    private void setStreamResponse(HttpServletResponse response, java.io.File file, String filename) throws UnsupportedEncodingException {
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        try (FileInputStream fileInputStream = new FileInputStream(file);
             BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {
            FileCopyUtils.copy(bufferedInputStream, bufferedOutputStream);
        } catch(Exception e){
        } 
    }
}
